// src/api/activity.ts
import { request } from './request'

export interface Activity {
  id: number
  name: string
  type: 'lottery' | 'sign' | 'other'
  status: '未开始' | '进行中' | '已结束'
  startTime: string
  endTime: string
  image?: string // base64 or URL
}

/* -------------------- mock state -------------------- */
// 初始 mock 数据
let mockActivities: Activity[] = [
  {
    id: 1,
    name: '大转盘活动',
    type: 'lottery',
    status: '进行中',
    startTime: '2025-09-20 10:00:00',
    endTime: '2025-09-30 23:59:59',
    image: ''
  },
  {
    id: 2,
    name: '签到有礼',
    type: 'sign',
    status: '未开始',
    startTime: '2025-10-01 00:00:00',
    endTime: '2025-10-07 23:59:59',
    image: ''
  }
]

let nextActivityId = 3

/* -------------------- API -------------------- */

export async function getActivityList(): Promise<Activity[]> {
  // 返回深拷贝，避免外部误修改原数组
  const snapshot = JSON.parse(JSON.stringify(mockActivities)) as Activity[]
  return request<Activity[]>({ url: '/activities/list', method: 'GET' }, snapshot)
}

export async function addActivity(activity: Omit<Activity, 'id'>): Promise<Activity> {
  const newAct: Activity = { ...activity, id: nextActivityId++ }
  mockActivities.push(newAct)
  // 返回深拷贝
  const out = JSON.parse(JSON.stringify(newAct)) as Activity
  return request<Activity>({ url: '/activities/add', method: 'POST', data: out }, out)
}

export async function updateActivity(activity: Activity): Promise<Activity> {
  const idx = mockActivities.findIndex(a => a.id === activity.id)
  if (idx !== -1) {
    mockActivities[idx] = { ...activity }
  } else {
    // 如果没找到则追加（容错）
    mockActivities.push({ ...activity })
  }
  const out = JSON.parse(JSON.stringify(activity)) as Activity
  return request<Activity>({ url: '/activities/update', method: 'PUT', data: out }, out)
}

export async function deleteActivity(id: number): Promise<boolean> {
  mockActivities = mockActivities.filter(a => a.id !== id)
  return request<boolean>({ url: `/activities/delete/${id}`, method: 'DELETE' }, true)
}

/* 仅开发时查看当前 mock（可选） */
export function __getMockActivitiesForDev(): Activity[] {
  return mockActivities
}
